package com.darin.cl.http;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.util.Args;

public class CLFileBody extends FileBody {
	private long mTransferred = 0;
	private CLHttpProcessListener mListener;
	private Object mFlag;

	public CLFileBody(File file,Object flag) {
		super(file, ContentType.DEFAULT_BINARY,file.getName());
		this.mFlag=flag;
	}

	@Override
	public void writeTo(OutputStream out) throws IOException {
		Args.notNull(out, "Output stream");
		InputStream in = new FileInputStream(getFile());
		try {
			byte[] tmp = new byte[4096];
			int l;
			while ((l = in.read(tmp)) != -1) {
				out.write(tmp, 0, l);
				mTransferred += l;
				if (mListener != null) {
					mListener.onProcessChange(mTransferred,getContentLength(),mFlag);
				}
			}
			out.flush();
		} finally {
			in.close();
		}
	}

	

	public void setUpLoadProgressListener(CLHttpProcessListener listener) {
		this.mListener = listener;
	}

}
